﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;

namespace Async_Socket_Server
{
    public partial class FormSendComplex : Form
    {

        public delegate void SendComplexDelegate(string text);
        public SendComplexDelegate SendComplexCallback;
        public string LastSentMsg = "";
        private List<string> SentStrings = new List<string>();


        public FormSendComplex()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SendComplexCallback(textBox1.Text);
            AddToList(textBox1.Text);
        }

        private void FormSendComplex_Load(object sender, EventArgs e)
        {
            Deserialize();
            comboBox1.Items.AddRange(SentStrings.ToArray());
            comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
        }

        private void AddToList(string text)
        {
            if (text != LastSentMsg)
            {
                foreach (string i in SentStrings)
                {
                    if (i == text) { LastSentMsg = text; return; }
                }

                if (SentStrings.Count >= 20)
                {
                    SentStrings.RemoveAt(0);
                    comboBox1.Items.RemoveAt(0);
                }

                SentStrings.Add(text);
                comboBox1.Items.Add(text);
            }

            LastSentMsg = text;
        }

        private void Deserialize()
        {
            StringReader reader = new StringReader(Properties.Settings.Default.SendComplexTexts);
            XmlSerializer serializer = new XmlSerializer(SentStrings.GetType());

            object obj = serializer.Deserialize(reader);
            SentStrings = (List<String>)obj;
        }

        private void Serialize()
        {
            XmlSerializer serializer = new XmlSerializer(SentStrings.GetType());
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter writer = new StringWriter(stringBuilder);

            serializer.Serialize(writer, SentStrings);

            Properties.Settings.Default.SendComplexTexts = stringBuilder.ToString();
            Properties.Settings.Default.Save();
        }

        private void FormSendComplex_FormClosing(object sender, FormClosingEventArgs e)
        {
            Serialize();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = comboBox1.SelectedItem.ToString();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            comboBox1.Text = textBox1.Text;
        }
        
    }
}
